import {Component, OnInit, AfterViewInit, ViewChild} from '@angular/core';
import {FormBuilder, FormGroup, Validators} from '@angular/forms';

import {RouterService} from '@kylin/router';
import {LoginService} from './login.service';
import {NzMessageService} from 'ng-zorro-antd';
import {CacheService} from '@kylin/cache';
import * as _ from 'lodash';
import {TokenService} from '@kylin/core';

@Component({
    templateUrl: './login.component.html',
    styleUrls: ['./login.component.less']
})

export class LoginComponent implements OnInit, AfterViewInit {

    loginForm: FormGroup;
    loading = false;
    state = true;
    @ViewChild('verificationCode', {static: true}) verificationCode;
    loginByPhone = false;

    constructor(private routerService: RouterService,
                private fb: FormBuilder,
                private loginService: LoginService,
                private message: NzMessageService,
                private cacheService: CacheService,
                private tokenService: TokenService
    ) {

    }

    /**
     * 此方法用创建响应式表单
     */
    ngOnInit(): void {
        this.loginFormInit();
    }

    ngAfterViewInit(): void {

    }

    private loginFormInit() {
        this.loginForm = this.fb.group({
            username: [null, [Validators.required]],
            password: [null, [Validators.required]],
            validCode: [null, [Validators.required]]
        });
    }

    /**
     * 此方法用来提交登陆表单
     */
    submitForm(): void {

        for (const i in this.loginForm.controls) {
            this.loginForm.controls[i].markAsDirty();
            this.loginForm.controls[i].updateValueAndValidity();
        }

        this.loading = true;
        const data = {};
        _.forEach(this.loginForm.value, (value, key) => {
            if (key === 'validCode' && !!value) {
                data['deviceId'] = value['deviceId'];
                data['validCode'] = value['validCode'];
            } else {
                data[key] = value;
            }
        });
        this.loginService.doLogin(data)
            .then(res => {
                this.loading = false;
                if (res.resp_code === '10000') {
                    this.handleLoginSuccess(res);
                } else {
                    this.message.error(res.resp_msg);
                    this.fetchVerificationCode();
                }
            })
            .catch(err => {
                this.loading = false;
                // this.message.create('error', `登陆失败`);
            });
    }

    /**
     *  hex 2019/07/25
     *  提出成功登录后的处理内容，和手机登录共用
     */
    handleLoginSuccess = (res: any) => {
        this.cacheService.clear();
        this.tokenService.set(res.data.access_token);
        // this.cacheService.set('access_token', res.data.access_token);
        this.cacheService.set('refresh_token', res.data.refresh_token);
        const expires_time = new Date().getTime() + res.data.expires_in * 1000;
        this.cacheService.set('expires_time', expires_time);

        this.message.success('登录成功!', {nzDuration: 1000});
        setTimeout(() => {
            this.routerService.navigate('/home');
        }, 1000)
    };

    private fetchVerificationCode() {
        this.verificationCode.fetchValidCode();
    }

}

